package com.huixin.powermonitor.controller;

import com.huixin.powermonitor.DTO.DeviceQueryParams;
import com.huixin.powermonitor.DTO.Device_TU_DTO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huixin.powermonitor.DTO.DeviceDTO;
import com.huixin.powermonitor.common.QueryPageParam;
import com.huixin.powermonitor.common.Result;
import com.huixin.powermonitor.entity.*;
import com.huixin.powermonitor.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author huixin
 * @since 2025-07-08
 */
@CrossOrigin(originPatterns = "*", maxAge = 3600)
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceCategoryRelationsService deviceCategoryRelationsService;
    @Autowired
    private DeviceCategoriesService deviceCategoriesService;
    @Autowired
    private DeviceDocumentsService deviceDocumentsService;
    @Autowired
    private RealTimeDataService realTimeDataService;
    @Autowired
    private HistoryDataService historyDataService;


    //    @GetMapping("/page_device")
//    public Result showDevice(){
//        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
//        List<Device> deviceList = deviceService.list();
//        return Result.suc(deviceList);
//    }
//}
//    @GetMapping("/pagedto")
//    public Result showDevicedto(){
//        List<Device> deviceList = deviceService.list();
//        List<DeviceDTO> dtoList = new ArrayList<>();
//        for (Device device : deviceList) {
//            DeviceCategoryRelations relations = deviceCategoryRelationsService.getById(device.getDeviceId());
//            DeviceCategories categories = deviceCategoriesService.getById(relations.getCategoryId());
//            DeviceDTO deviceDTO = new DeviceDTO(device.getDeviceId(),device.getDeviceName(),
//                    device.getDeviceCode(),device.getDeviceType(),device.getVoltageLevel(),
//                    device.getRegion(),device.getInstallationLocation(),
//                    categories.getCategoryName(),categories.getCategoryDescription());
//            dtoList.add(deviceDTO);
//        }
//        return Result.suc(dtoList);
//    }
    @GetMapping("/pagedto")
    public Result showDevicedto(
            @RequestParam(required = false) String deviceName,
            @RequestParam(required = false) String voltageLevel,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        Page<Device> page = new Page<>(pageNum, pageSize);

        Page<Device> devicePage = deviceService.page(page);


        List<DeviceDTO> dtoList = new ArrayList<>();
        for (Device device : devicePage.getRecords()) {
            DeviceCategoryRelations relations = deviceCategoryRelationsService.getById(device.getDeviceId());
            if (relations == null) continue;

            DeviceCategories categories = deviceCategoriesService.getById(relations.getCategoryId());
            if (categories == null) continue;

            DeviceDTO deviceDTO = new DeviceDTO(
                    device.getDeviceId(),
                    device.getDeviceName(),
                    device.getDeviceCode(),
                    device.getDeviceType(),
                    device.getVoltageLevel(),
                    device.getRegion(),
                    device.getInstallationLocation(),
                    categories.getCategoryName(),
                    categories.getCategoryDescription()
            );
            dtoList.add(deviceDTO);
        }


        Page<DeviceDTO> dtoPage = new Page<>();
        dtoPage.setRecords(dtoList);
        dtoPage.setCurrent(devicePage.getCurrent());
        dtoPage.setSize(devicePage.getSize());
        dtoPage.setTotal(devicePage.getTotal());

        return Result.suc(dtoPage);

    }

    @PostMapping("/listPage")
    public Result findDevice(@RequestBody QueryPageParam params) {

        int pageNum = params.getPageNum();
        int pageSize = params.getPageSize();
        Page<Device> page = new Page<>(pageNum, pageSize);
        HashMap<String,Object> map = params.getParam();

        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();

        if (map.containsKey("deviceName") && StringUtils.isNotBlank(map.get("deviceName").toString()))  {
            String deviceName = map.get("deviceName").toString();
            queryWrapper.like(Device::getDeviceName, deviceName);
        }

        if (map.containsKey("voltageLevel") && StringUtils.isNotBlank(map.get("voltageLevel").toString()))  {
            String voltageLevel = map.get("voltageLevel").toString();
            queryWrapper.like(Device::getVoltageLevel, voltageLevel);
        }

        if (map.containsKey("categoryName") && StringUtils.isNotBlank(map.get("categoryName").toString()))  {
            String categoryName = map.get("categoryName").toString();
            queryWrapper.like(Device::getCategoryName, categoryName);
        }

        IPage<Device> resultPage = deviceService.page(page, queryWrapper);
        List<Device> records = resultPage.getRecords();
        for (Device record : records) {
            LambdaQueryWrapper<DeviceCategoryRelations> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DeviceCategoryRelations::getDeviceId, record.getDeviceId());
            DeviceCategoryRelations relations = deviceCategoryRelationsService.getOne(queryWrapper1);
            if (relations == null) continue;
            DeviceCategories categories = deviceCategoriesService.getById(relations.getCategoryId());
            if (categories == null) continue;
            record.setCategoryName(categories.getCategoryName());
            record.setCategoryDescription(categories.getCategoryDescription());
        }
        return Result.suc(resultPage.getTotal(),records);
    }

    //    @GetMapping("/find_device")
//    public Result findDevice(@RequestBody DeviceQueryParams params) {
//        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
//
//        if (StringUtils.hasText(params.getDeviceName())) {
//            queryWrapper.like(Device::getDeviceName, params.getDeviceName());
//        }
//
//        if (StringUtils.hasText(params.getVoltageLevel())) {
//            queryWrapper.like(Device::getVoltageLevel, params.getVoltageLevel());
//        }
//
//        Page<Device> page = new Page<>(params.getPageNum(), params.getPageSize());
//        Page<Device> resultPage = deviceService.page(page, queryWrapper);
//
//        return Result.suc(resultPage);
//    }
    @GetMapping("/page")
    public Result showDevice(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        // 创建分页对象
        Page<Device> page = new Page<>(pageNum, pageSize);

        // 执行分页查询
        Page<Device> devicePage = deviceService.page(page);

        // 构建分页结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", devicePage.getRecords());
        resultMap.put("total", devicePage.getTotal());
        resultMap.put("pages", devicePage.getPages());
        resultMap.put("current", devicePage.getCurrent());
        resultMap.put("size", devicePage.getSize());
        return Result.suc(resultMap);
    }

    @GetMapping("/document/page")
    public Result showDocument(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<DeviceDocuments> page = new Page<>(pageNum, pageSize);
        IPage<DeviceDocuments> deviceDocumentsPage = deviceDocumentsService.page(page);
        List<DeviceDocuments> deviceDocuments = deviceDocumentsPage.getRecords();
        for (DeviceDocuments deviceDocument : deviceDocuments) {
            deviceDocument.setDeviceName(deviceService.getById(deviceDocument.getDeviceId()).getDeviceName());
        }
        return Result.suc(deviceDocumentsPage);
    }

    @GetMapping("/r_device_state")
    public Result device_state(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 创建分页对象
        Page<RealTimeData> page = new Page<>(pageNum, pageSize);

        // 执行分页查询
        IPage<RealTimeData> realTimeDataPage = realTimeDataService.page(page);

        // 获取当前页的数据
        List<RealTimeData> records = realTimeDataPage.getRecords();

        // 设置设备名称
        for (RealTimeData r : records) {
            Device device = deviceService.getById(r.getDeviceId());
            if (device != null) {
                r.setDeviceName(device.getDeviceName());
            } else {
                r.setDeviceName("未知设备");
            }
        }

        // 返回分页结果（使用 IPage 作为 data）
        return Result.suc(realTimeDataPage);
    }

    @GetMapping("/his_device_state")
    public Result hisDeviceState(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 创建分页对象
        Page<HistoryData> page = new Page<>(pageNum, pageSize);

        // 分页查询历史数据
        IPage<HistoryData> historyDataPage = historyDataService.page(page);

        // 获取当前页的数据列表
        List<HistoryData> records = historyDataPage.getRecords();

        // 设置设备名称
        for (HistoryData historyData : records) {
            Device device = deviceService.getById(historyData.getDeviceId());
            if (device != null) {
                historyData.setDeviceName(device.getDeviceName());
            } else {
                historyData.setDeviceName("未知设备");
            }
        }

        // 返回分页结果（使用 IPage 作为 data）
        return Result.suc(historyDataPage);
    }

    @PostMapping("/show_tu")
    public Result show_tu() {
        List<Device> deviceList = deviceService.list();
        for (Device d : deviceList) {
            Device_TU_DTO deviceTuDto = new Device_TU_DTO();
            deviceTuDto.setDeviceName(d.getDeviceName());
            deviceTuDto.setVoltageLevel(d.getVoltageLevel());

        }
        return Result.suc();
    }

    @PostMapping("/save")
    public Result addDevice(@RequestBody Device device) {

        deviceService.save(device);

        Integer newDeviceId = device.getDeviceId();

        LambdaQueryWrapper<Device> nameCheckWrapper = new LambdaQueryWrapper<>();
        nameCheckWrapper.eq(Device::getDeviceName, device.getDeviceName());

        LambdaQueryWrapper<DeviceCategories> categoryWrapper = new LambdaQueryWrapper<>();
        categoryWrapper.eq(DeviceCategories::getCategoryName, device.getCategoryName());
        DeviceCategories category = deviceCategoriesService.getOne(categoryWrapper, false); // 允许返回null
        if (category == null) {
            return Result.fail("类型不存在");
        }

        DeviceCategoryRelations relation = new DeviceCategoryRelations();
        relation.setDeviceId(newDeviceId);
        relation.setCategoryId(category.getCategoryId());
        deviceCategoryRelationsService.save(relation);

        return Result.suc();
    }


    @Transactional
    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除设备")
    public Result deleteBatch(@RequestBody Long[] id) {
        try {
            LambdaQueryWrapper<DeviceCategoryRelations> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(DeviceCategoryRelations::getDeviceId, Arrays.asList(id));
            deviceCategoryRelationsService.remove(wrapper);
            deviceService.removeByIds(Arrays.asList(id));
            return Result.suc("批量删除成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("删除失败: " + e.getMessage());
        }


    }
    @PostMapping("/real-time-data/listPage")
    public Result device_state(@RequestBody QueryPageParam params)  {

        int pageNum = params.getPageNum();
        int pageSize = params.getPageSize();

        Page<RealTimeData> page = new Page<>(pageNum, pageSize);
        HashMap<String,Object> map = params.getParam();
        LambdaQueryWrapper<RealTimeData> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper= new LambdaQueryWrapper<>();
        if( map.containsKey("deviceName") && StringUtils.isNotBlank(map.get("deviceName").toString()))  {
            String deviceName = map.get("deviceName").toString();
            deviceLambdaQueryWrapper.like(Device::getDeviceName,deviceName);
            List<Device> deviceList=deviceService.list(deviceLambdaQueryWrapper);
//            queryWrapper.like(RealTimeData::getDeviceId, deviceService.getOne(new LambdaQueryWrapper<Device>().like(Device::getDeviceName, deviceName)).getDeviceId());
            for(Device d:deviceList){
                queryWrapper.like(RealTimeData::getDeviceId,d.getDeviceId());
            }
        }

//        if( map.containsKey("voltageLevel") && StringUtils.isNotBlank(map.get("voltageLevel").toString()))  {
//            String voltageLevel = map.get("voltageLevel").toString();
//            queryWrapper.like(RealTimeData::getVoltage, voltageLevel);
//        }
//
//        if(map.containsKey("temperature") && StringUtils.isNotBlank(map.get("temperature").toString()))  {
//            String temperature = map.get("temperature").toString();
//            queryWrapper.like(RealTimeData::getTemperature, temperature);
//        }

        IPage<RealTimeData> realTimeDataPage = realTimeDataService.page(page, queryWrapper);
        List<RealTimeData> records = realTimeDataPage.getRecords();
        for(RealTimeData record : records) {
            Device device = deviceService.getById(record.getDeviceId());
            if (device != null) {
                record.setDeviceName(device.getDeviceName());
            } else {
                record.setDeviceName("未知设备");
            }
        }
        return Result.suc(realTimeDataPage.getTotal(),records);
    }
//    @PostMapping("/add")
//    public Result add(@RequestBody RealTimeData data) {
//        realTimeDataService.save(data);
//        return Result.suc("添加成功");
//    }

}
